<template>
  <div class="page gridmap-page">
    <nav-bar title="网格地图"></nav-bar>
    <div class="gridmap-body">
      <div class="gridmap-mapmain" id="container"></div>
      <div class="gridmap-event" @click="gridToggle">{{ gridBtnText }}</div>
      <div class="gridmap-bottom" v-if="curGridInfo">
        <p class="gridmap-name">管辖网格：{{ curGridInfo.gridName }}</p>
        <van-row class="gridmap-regist-list">
          <van-col :span="12" class="gridmap-regist-item">
            登记人口数量：
            <span class="gridmap-regist-num">{{ curGridInfo.personCount }}</span>
          </van-col>
          <van-col :span="12" class="gridmap-regist-item">
            登记房屋数量：
            <span class="gridmap-regist-num">{{ curGridInfo.houseCount }}</span>
          </van-col>
          <van-col :span="12" class="gridmap-regist-item">
            登记楼栋数量：
            <span class="gridmap-regist-num">{{ curGridInfo.buildCount }}</span>
          </van-col>
          <van-col :span="12" class="gridmap-regist-item">
            登记单位数量：
            <span class="gridmap-regist-num">{{ curGridInfo.companyCount }}</span>
          </van-col>
        </van-row>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import mapPlugin from '@/libs/mapPlugin'
import gridMap from '@/api/gridMap'
export default {
  data() {
    return {
      gridBtnText: '网格事件',
      map: null,
      center: [],
      markers: [],
      overlayGroup: null,
      gridDatas: [],
      polygonPath: [],
      gridsMarkers: [],
      eventDatas: [
        {
          eventName: '待处置事件一',
          eventStatus: '1',
          longitude: 115.918583,
          latitude: 28.638091
        },
        {
          eventName: '处置中事件一',
          eventStatus: '2',
          longitude: 115.918583,
          latitude: 28.639051
        },
        {
          eventName: '即将超时事件一',
          eventStatus: '3',
          longitude: 115.920165,
          latitude: 28.638091
        },
        {
          eventName: '已超时事件一',
          eventStatus: '4',
          longitude: 115.919583,
          latitude: 28.638091
        }
      ],
      buildingDatas: [],
      buildingMarkers: [],
      eventMarkers: [],
      eventImgObj: {
        1: 'underdisposal',
        2: 'pending-disposal',
        // 3: 'about-to-timeout',
        4: 'timedout'
      },
      distanceMarker: null,
      distance: null,
      curGridInfo: null,
      myMarker: [],
      myPos: null
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    }),
    curPersonImg() {
      return this.user.personImage
        ? this.$config.ImageURl + this.user.personImage
        : 'https://img01.yzcdn.cn/vant/cat.jpeg'
    }
  },
  mounted() {
    this.map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 16,
      features: ['bg', 'road', 'building']
    })
    this.getGridScopes()
    this.getGridRegister()
    this.getGridBuild()
    this.setMyLocation()
  },
  methods: {
    getGridScopes() {
      // 获取网格范围
      gridMap.Map.gridScope({ gridCode: this.user.gridCode }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.gridDatas = data
          this.setGridCenter()
          this.setGridsPolygon()
          this.setGridMarker()
          this.curGridCode = this.gridDatas[0].gridCode
        }
      })
    },
    getGridRegister() {
      // 获取辖区网格内登记数量
      gridMap.Map.gridRegisterCount({ gridCode: this.user.gridCode }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.curGridInfo = data
        }
      })
    },
    getGridBuild() {
      // 根据网格编码获取楼栋
      gridMap.Map.build({ gridCode: this.user.gridCode }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.buildingDatas = data
          this.setBuildingMarker()
        }
      })
    },
    gridToggle() {
      // 点击网格事件或者管辖详情
      if (this.gridBtnText === '网格事件') {
        this.map.remove(this.buildingMarkers)
        this.map.remove(this.gridsMarkers)
        this.setEventMarker()
      } else {
        mapPlugin.walking(this.map)
        this.removeDistanceMarker()
        this.map.remove(this.eventMarkers)
        this.map.add(this.gridsMarkers)
        this.map.add(this.buildingMarkers)
        this.map.setFitView(this.buildingMarkers)
      }
      this.gridBtnText = this.gridBtnText === '网格事件' ? '管辖详情' : '网格事件'
    },
    setGridCenter() {
      // 设置中心点
      this.center = [this.gridDatas[0].longitude, this.gridDatas[0].latitude]
      this.map.setCenter(this.center)
      this.map.setZoom(16)
    },
    setGridsPolygon() {
      // 画网格矢量图形
      this.polygonPath = []
      this.gridDatas.forEach(item => {
        if (item.scope) {
          this.polygonPath.push(
            JSON.parse(JSON.parse(item.scope)[0]).map(o => {
              return new AMap.LngLat(o[0], o[1])
            })
          )
        }
      })
      const polygon = new AMap.Polygon({
        path: this.polygonPath,
        fillColor: 'transparent', // 多边形填充颜色
        borderWeight: 2, // 线条宽度，默认为 1
        strokeColor: '#E28556' // 线条颜色
      })
      this.map.add(polygon)
    },
    setGridMarker() {
      // 设置网格标记
      this.gridsMarkers = []
      this.gridDatas.forEach(item => {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(item.longitude, item.latitude),
          content: "<div class='marker-info grid-info'>" + item.gridName + '</div>'
        })
        this.gridsMarkers.push(marker)
      })
      if (this.gridsMarkers.length) {
        this.overlayGroup = new AMap.OverlayGroup(this.gridsMarkers)
        this.map.add(this.overlayGroup)
        this.map.setFitView(this.gridsMarkers)
      }
    },
    setMyLocation() {
      // 设置我的位置标记
      mapPlugin.geolocation(res => {
        this.myPos = [res.position.lng, res.position.lat]
        this.myMarker = new AMap.Marker({
          position: new AMap.LngLat(res.position.lng, res.position.lat),
          content: `<img src="${this.curPersonImg}" class="my-location-marker" alt="">`
        })
        this.map.add(this.myMarker)
      }, true)
    },
    setEventMarker() {
      const paramsData = {
        eventStatus: '2|3|7|8',
        eventDescription: '',
        recordSize: 0,
        pageSize: 999
      }
      // 获取事件列表
      gridMap.Map.eventList(paramsData).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          console.log(data)
          this.eventDatas = data.list
          // 设置事件标记
          this.eventMarkers = []
          this.eventDatas.forEach(item => {
            if (item.isTimeOut === '1') {
              // 已超时
              item.status = '4'
            }
            if (item.eventStatus === '2' || item.eventStatus === '7') {
              // 待处置
              item.status = '1'
            } else if (item.eventStatus === '3' || item.eventStatus === '8') {
              // 处置中
              item.status = '2'
            }
            const img = require(`@/assets/images/gridMap/event-${this.eventImgObj[item.status * 1]}@2x.png`)
            const content = `
              <div class="amap-marker-event-content">
                  <img src="${img}" class="event-marker" alt="">
                  <div class="marker-info event-name event-name-${item.status}">${item.eventName}</div>
              </div>`
            var marker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              content: content
            })
            this.eventMarkers.push(marker)
            // 点击事件标注，获取步行导航路线
            marker.on('click', e => {
              const isEventMarker = marker.getContent().includes('amap-marker-event-content')
              const distancePos = [(this.myPos[0] + e.lnglat.lng) / 2, (this.myPos[1] + e.lnglat.lat) / 2]
              if (isEventMarker) {
                this.removeDistanceMarker()
                this.walking = mapPlugin.walking(this.map, this.myPos, [e.lnglat.lng, e.lnglat.lat], async res => {
                  this.distanceMarker = new AMap.Marker({
                    position: new AMap.LngLat(distancePos[0], distancePos[1]),
                    content: `<div class="marker-info distance-info">距离我${res.routes[0].distance}米<span class="handle-event">处置</span></div>`
                  })
                  this.map.add(this.distanceMarker)
                  this.distanceMarker.on('click', e => {
                    this.$router.push(`/event/detail?eventCode=${item.eventCode}`)
                  })
                })
              }
            })
          })
          if (this.eventMarkers.length) {
            this.overlayGroup = new AMap.OverlayGroup(this.eventMarkers)
            this.map.add(this.overlayGroup)
            this.map.setFitView(this.eventMarkers)
          }
        }
      })
    },
    removeDistanceMarker() {
      // 清楚距离我提示文字
      if (this.distanceMarker) {
        this.map.remove(this.distanceMarker)
      }
    },
    setBuildingMarker() {
      // 设置楼栋标记
      this.buildingMarkers = []
      const buildImg = require('@/assets/images/gridMap/building-location@2x.png')
      this.buildingDatas.forEach(item => {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(item.longitude, item.latitude),
          content: `<div class="buid-marker-content">
           <img src="${buildImg}" class="build-marker" alt="">
           <div class="marker-info building-info">${item.buildName}</div>
          </div>`
        })
        this.buildingMarkers.push(marker)
        marker.on('click', e => {
          this.$router.push({ path: `/gridmap/buildingDetail?buildCode=${item.buildCode}` })
        })
      })
      if (this.buildingMarkers.length) {
        this.overlayGroup = new AMap.OverlayGroup(this.buildingMarkers)
        this.map.add(this.overlayGroup)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/assets/style/gridmap/index.less';
</style>
